import React, {memo, useCallback, useEffect, useState} from 'react';
import {AddFriendWrapper} from "./style";
import {Button, Image, Input} from "antd";
import setMessage from "@/utils/setMessage";
import {createFriend, getFriendById, updateFriend} from "@/network/friend.request";
import {withRouter} from "react-router";

function AddFriend(props) {
  const [name, setName] = useState("");
  const [desc, setDesc] = useState("");
  const [link, setLink] = useState("");
  const [avatar, setAvatar] = useState("");
  const [friendId, setFriendId] = useState(0);

  useEffect(() => {
    setFriendId(props.match.params["f_id"])
  }, [props.match.params])

  useEffect(() => {
    if (String(friendId) === "0") { // 创建
      setName("");
      setDesc("");
      setLink("");
      setAvatar("");
    } else {
      getFriendById(friendId).then(res => {
        setName(res.name);
        setDesc(res.friendDesc);
        setLink(res.link);
        setAvatar(res.avatar);
      }).catch(console.log)
    }
  }, [friendId])

  const clearInput = useCallback(() => {
    setName("");
    setDesc("");
    setLink("");
    setAvatar("");
  }, []);

  const saveFriend = useCallback(() => {
    if (name.trim() !== "" && desc.trim() !== "" && link.trim() !== "" && avatar.trim() !== "") {
      if (String(friendId) === "0") { // 新建
        createFriend(name, desc, link, avatar).then(res => {
          res.affectedRows && setMessage("保存成功", "success");
          !res.affectedRows && setMessage("该好友已存在", "error");
        }).catch(error => {
          setMessage("保存失败", "error");
          console.log(error)
        })
      } else { // 修改
        updateFriend(friendId, name, desc, link, avatar).then(res => {
          res.affectedRows && setMessage("修改成功", "success");
          !res.affectedRows && setMessage("该好友已存在", "error");
        }).catch(error => {
          setMessage("修改失败", "error");
          console.log(error)
        })
      }
    } else {
      setMessage("输入要素不完整, 保存失败", "error");
    }
  }, [name, desc, link, avatar, friendId])

  return (
    <AddFriendWrapper>
      <Input value={name} onChange={e => setName(e.target.value)} className="my-7" placeholder="好友昵称"/>
      <Input value={desc} onChange={e => setDesc(e.target.value)} className="my-7" placeholder="好友简介"/>
      <Input value={link} onChange={e => setLink(e.target.value)} className="my-7" placeholder="好友外链"/>
      <Input value={avatar} onChange={e => setAvatar(e.target.value)} className="my-7" placeholder="好友头像"/>
      <Image width={200}
             src={avatar}
             fallback=""
      />
      <div className="pt-8 pl-6">
        <Button className="mr-7" onClick={clearInput}>清空输入</Button>
        <Button type="primary" onClick={saveFriend}>保存好友</Button>
      </div>
    </AddFriendWrapper>
  )
}

export default memo(withRouter(AddFriend))
